﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ObserverPattern
{
    class Program1
    {
        static void Main1(string[] args)
        {
            Light light = new Light();
            Car car = new Car();
            car.Name = "轿车";
            Car car1 = new Car();
            car1.Name = "公交车";
            Car car2 = new Car();
            car2.Name = "救护车";
            light.AddObserver(car);
            light.AddObserver(car1);
            light.AddObserver(car2);
            while (true)
            {
                light.ChangeColor();
                Console.WriteLine("当前交通灯的颜色:" + light.Color);

                Console.WriteLine(car.Name + "当前状态：" + car.Status);
                Console.WriteLine(car1.Name + "当前状态：" + car1.Status);
                Console.WriteLine(car2.Name + "当前状态：" + car2.Status);

                Thread.Sleep(5000);
            }
        }
    }

    abstract class Subject
    {
        List<Observer> observers = new List<Observer>();
        public void AddObserver(Observer observer)
        {
            this.observers.Add(observer);
        }
        public void Publish()
        {
            foreach (Observer observer in observers)
            {
                observer.Update(this);
            }
        }
    }

    abstract class Observer
    {
        public abstract void Update(Subject subject);
    }

    class Light : Subject
    {
        public string Color { get; set; }

        public void ChangeColor()
        {
            switch (Color)
            {
                case "red":
                    Color = "green";
                    break;
                case "green":
                    Color = "red";
                    break;
                default:
                    Color = "red";
                    break;

            }
            this.Publish();
        }
    }

    class Car : Observer
    {
        public string Name { get; set; }
        public string Status { get; set; }

        public override void Update(Subject subject)
        {
            Light light = subject as Light;

            switch (light.Color)
            {
                case "red":
                    Status = "stop";
                    break;
                case "green":
                    Status = "gogo";
                    break;
            }

        }
    }


}
